--[[
	pb数据的序列化与反序列化
]]

local M = {}

-- 包格式：
-------------------------
-- 第一个字节，包头长度，最多255，在回应包里含了retstr，这里需要注意
-- + 包头（主要是含协议名）
-- + 包体（利用包头的协议名去解包）
-------------------------

function M.c2spack(protobuf, msgname, msgbody, rid)
	return string.pack(">s1", protobuf.encode("c2sHead", {msgname = msgname, rid = rid,}))
			..protobuf.encode(msgname, msgbody)
	end

function M.c2sunpack(protobuf, msgbuf)
	-- msgbuf = tostring(msgbuf) -- 这里到底要不要使用 tosting，就看怎么调用的
	if msgbuf == "" then return nil, nil end
	local msgheadsize = msgbuf:byte(1)
	if msgbuf:len() < msgheadsize + 1 then
		return nil, nil			 
	end
	local msghead, msgbody = msgbuf:sub(2,1+msgheadsize), msgbuf:sub(2+msgheadsize)
	msghead = protobuf.decode("c2sHead", msghead, string.len(msghead))
	msgbody = protobuf.decode(msghead.msgname, msgbody, string.len(msgbody))
	return msghead, msgbody
end

function M.s2cpack(protobuf, msgname, retcode, retstr, msgbody)
	retcode = retcode or 0
	retstr = retstr or ''
	if retcode == 0 and msgbody then
		return string.pack(">s1", protobuf.encode("s2cHead", {msgname = msgname, retcode = retcode, retstr = retstr}))
			.. protobuf.encode(msgname, msgbody)
	else
		return string.pack(">s1", protobuf.encode("s2cHead", {msgname = msgname, retcode = retcode, retstr = retstr}))
	end
end	

function M.s2cunpack(protobuf, msgbuf)
	-- msgbuf = tostring(msgbuf) -- 这里都暂时不用tosting来处理吧
	local  msgheadsize = msgbuf:byte(1)
	if msgbuf:len() < msgheadsize + 1 then
		return nil, nil			 
	end
	local msghead, msgbody = msgbuf:sub(2,1+msgheadsize), msgbuf:sub(2+msgheadsize)

	msghead = protobuf.decode("s2cHead", msghead, string.len(msghead))
	if msghead.retcode == 0 then
		-- 错误码为0 ，才说明有包体
		msgbody = protobuf.decode(msghead.msgname, msgbody, string.len(msgbody))
	else
		msgbody = nil
	end
	return msghead, msgbody
end

return M